const validator=require('validator');
module.exports=function (done) {
	$.method('topic.add').check({
		author: {validate: v => validator.isMongoId(v)},
		title: {required: true},
		content: {required: true},
		tags: {validate: v => Array.isArray(v)}
	})
	$.method('topic.add').register(async function (params) {
		const topic=new $.model.Topic(params);
		return topic.save();
	});

	$.method('topic.get').check({
		_id: {required: true,validate: v => validator.isMongoId(v)}
	})
	$.method('topic.get').register(async function (params) {
		return $.model.Topic.findOne(params);
	});

	$.method('topic.list').check({
		author: {validate: v => validator.isMongoId(v)},
		tags:{validate:v=>Array.isArray(v)},
		skip: {validate:v=> v>=0},
		limit: {validate:v=>v>=0}
	})

	$.method('topic.list').register(async function (params) {
		const query={};
		if (params.author) query.author=params.author;
		if (params.tags) query.tags={$all: params.tags};
		let ret =  $.model.Topic.find(query,{
			author: 1,
			title: 1,
			createAt: 1,
			updateAt: 1,
			lastCommentedAt:1
		});
		if (params.skip) ret.skip(Number(params.skip));
		if (params.limit) ret.limit(Number(params.limit));
		return ret;
	});

	$.method('topic.update').check({
		_id: {required: true,validate: v => validator.isMongoId(v)},
		tags:{validate:v=>Array.isArray(v)}
	});

	$.method('topic.update').register(async function (params) {
		const update={};
		if (params.title) update.title=params.title;
		if (params.content) update.title=params.content;
		if (params.tags) update.tags=params.tags;
		return $.model.Topic.update({_id:params._id},params);
	});
	
	$.method('topic.delete').register(async function (params) {
		return $.model.Topic.remove({_id:params._id});
	});

	// post /api/topic/:topic_id/comment/add
	$.method('topic.comment.add').check({
		author: {validate: v => validator.isMongoId(v)},
		content:{required:true}
	});
	$.method('topic.comment.add').register(async function (params) {
		return $.model.Topic.update({_id: params._id},{
			$push: {
				comments: {
					author:params.author,
				    content:params.content
			}}
		});
	});
	// delete /api/topic/:topic_id/comment/:comment_id 
	$.method('topic.comment.delete').check({
		_id: {required: true,validate: v => validator.isMongoId(v)},
		comment_id: {required: true,validate: v => validator.isMongoId(v)},
	});
	$.method('topic.comment.delete').register(async function (params) {
		return $.model.Topic.update({_id: params._id},{
			$pull: {'comments': {_id: params.comment_id}}
		});
	});

	done();
}